//
//  QDLinePathView.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/4/8.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit
import HandyJSON

private extension String {
    
    /// 线路规划的文字
    func linePathMessage(append value: String) -> NSAttributedString {
        
        //自己转为基础
        let baseAttribute = NSMutableAttributedString(string: self, attributes: [.font : Font.regular.font(size: 14),.foregroundColor: 153.ritl_color])
        
        //转换值的值
        let valueAttribute = NSAttributedString(string: value, attributes:[.font : Font.regular.font(size: 14),.foregroundColor: 102.ritl_color])
        
        baseAttribute.append(valueAttribute)
        return baseAttribute
    }
    
}


/// 线路规划的列表样式
final class QDLinePathTableViewCell: NWTableViewCell {
    
    /// 是不是起点
    var isFirst: Bool = false {
        willSet {
            signImageView.isHidden = !(newValue || isEnd)
            if newValue {
                signImageView.image = "metro_line_start".namedImage
            }
        }
    }
    
    /// 是不是终点
    var isEnd: Bool = false {
        willSet {
            signImageView.isHidden = !(newValue || isFirst)
            lineView.isHidden = newValue
            numberLabel.isHidden = newValue
            countLabel.isHidden = newValue
            if newValue {
                signImageView.image = "metro_line_end".namedImage
            }
        }
    }
    
    /// 显示起点/终点的标签
    private let signImageView = UIImageView()
    /// 显示站点名称的标签
    let titleLabel = UILabel()
    /// 显示时间的标签
    let timeLabel = UILabel()
    /// 显示更显的视图
    let lineView = UIView()
    /// 显示几号线的标签
    let numberLabel = UILabel()
    /// 显示路过站点以及时间的标签
    let countLabel = UILabel()
    /// 站点转换的视图
    private let circleImageView = UIImageView()
    /// 圆角的视图
    let circleView = UIView()
    
    override func buildView() {
        super.buildView()
        
        selectionStyle = .none
        titleLabel.textColor = QDColors.black
        titleLabel.font = Font.medium.font(size: 20)
        
        timeLabel.textColor = 102.ritl_color
        timeLabel.font = Font.regular.font(size: 12)
        
        numberLabel.textColor = .white
        numberLabel.textAlignment = .center
        numberLabel.layer.cornerRadius = 19.0 / 2.0
        numberLabel.clipsToBounds = true
        numberLabel.font = Font.regular.font(size: 12)
        
        countLabel.textColor = QDColors.theme
        countLabel.font = Font.regular.font(size: 14)
        
        circleView.layer.cornerRadius = 3.5
        circleImageView.image = "mero_cycle".namedImage
        
        contentView.addSubview(lineView)
        contentView.addSubview(titleLabel)
        contentView.addSubview(timeLabel)
        contentView.addSubview(circleImageView)
        circleImageView.addSubview(circleView)
        contentView.addSubview(signImageView)
        contentView.addSubview(numberLabel)
        contentView.addSubview(countLabel)
        
        signImageView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(14)
            make.top.equalToSuperview().offset(5)
            make.width.height.equalTo(18)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(43)
            make.top.equalToSuperview().offset(0)
            make.height.equalTo(28)
        }
        
        timeLabel.snp.makeConstraints { (make) in
            make.left.equalTo(titleLabel.snp.right).offset(4)
            make.top.equalToSuperview().offset(8)
            make.height.equalTo(17)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.width.equalTo(2)
            make.top.equalToSuperview().offset(19)
            make.left.equalToSuperview().offset(22)
            make.bottom.equalToSuperview()
        }
        
        circleImageView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(7)
            make.left.equalToSuperview().offset(16)
            make.width.equalTo(15)
            make.height.equalTo(13)
        }
        
        circleView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.height.equalTo(7)
        }
        
        numberLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(43)
            make.top.equalTo(titleLabel.snp.bottom).offset(21)
            make.height.equalTo(19)
            make.width.equalTo(43)
        }
        
        countLabel.snp.makeConstraints { (make) in
            make.left.equalTo(numberLabel.snp.right).offset(12)
            make.height.equalTo(20)
            make.centerY.equalTo(numberLabel)
        }
    }
}


/// 线路规划的模型
struct QDLinePathModel: HandyJSON {
    
    /// 站点信息
    struct QDLinePathStation: HandyJSON {
        /// 起点名称
        var startStation = ""
        /// 起点开启时间
        var startFirst = ""
        /// 起点结束时间
        var startLast = ""
        /// 线路描述
        var stationNums = ""
        /// 显示几号线
        var lineName = ""
        /// 线路的id
        var lineId = ""
        /// 花费的时间
        var costTime = ""
    }

    
    /// 总价格
    var price = ""
    /// 换乘次数
    var exchangeTimes = ""
    /// 总站数
    var totalStations = ""
    /// 线路
    var stationInfos = [QDLinePathStation]()
    /// 话费的总时间
    var totalTimes = ""
}





/// 路径规划的视图
final class QDLinePathView: NWPopWindow {

    /// 固定的高度
    private let constHeight = 20 + 138.5 + BarDistance.TabBar.safeDistance + 8 + 15.5
    /// 底层的白色装载视图
    private let containerView = UIView()
    /// 关闭按钮
    private let closeButton = UIButton()
    /// 列表
    private let tableView = UITableView()
    /// 分割线
    private let lineView = UIView()
    /// 显示详细信息的标签
    private let pricelabel = UILabel()
    /// 显示换成信息的标签
    private let changedLabel = UILabel()
    /// 显示总计车站数的标签
    private let sumLabel = UILabel()
    /// 显示预计时间的标签
    private let timeLabel = UILabel()
    /// 显示购票按钮
    let bottomButton = UIButton()
    
    /// 数据
    private var linePath = QDLinePathModel() {
        willSet {//修改实行
            
            // tableView的
            let lastHeight = 28
            let moreHeight = (60 + 28) * (newValue.stationInfos.count - 1)
            let tableViewHeight = lastHeight + moreHeight
            
            //计算自身的高度
            containerView.ritl_height = CGFloat(tableViewHeight) + constHeight
        }
        didSet {//刷新视图
            tableView.reloadData()
        }
    }
    
    /// 更新数据
    func updateMessage(linePath: QDLinePathModel) {
        self.linePath = linePath
        
        //进行信息设置
        pricelabel.attributedText = "票价：".linePathMessage(append: "\(linePath.price)元")
        changedLabel.attributedText = "换乘：".linePathMessage(append: "\(linePath.exchangeTimes)次")
        sumLabel.attributedText = "共计：".linePathMessage(append: "\(linePath.totalStations)站")
        timeLabel.attributedText = "预计时间：".linePathMessage(append: linePath.totalTimes)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        containerView.backgroundColor = .white
        containerView.layer.cornerRadius = 8
        containerView.frame = CGRect(x: 0, y: ritl_height, width: ritl_width, height: 20 + 138.5 + BarDistance.TabBar.safeDistance + containerView.layer.cornerRadius + 400)
        
        closeButton.adjustsImageWhenHighlighted = false
        closeButton.setImage("metro_close".namedImage, for: .normal)
        closeButton.addTarget(self, action: #selector(closeButtonDidTap), for: .touchUpInside)
        
        lineView.backgroundColor = 235.ritl_color
        
        bottomButton.setTitle("购票", for: .normal)
        bottomButton.setTitleColor(.white, for: .normal)
        bottomButton.clipsToBounds = true
        bottomButton.layer.cornerRadius = 22
        bottomButton.titleLabel?.font = Font.medium.font(size: 16)
        let layer = CAGradientLayer()
        layer.colors = [QDColors.theme.cgColor,#colorLiteral(red: 0.4509803922, green: 0.8705882353, blue: 0.5215686275, alpha: 1).cgColor]
        layer.position = .zero
        layer.anchorPoint = .zero
        layer.startPoint = CGPoint(x: 1, y: 0.5)
        layer.endPoint = CGPoint(x: 0, y: 0.5)
        let width = UIScreen.main.bounds.width - 40
        layer.bounds = CGRect(origin: .zero, size: CGSize(width: width, height: 44))
        bottomButton.layer.insertSublayer(layer, at: 0)

        tableView.dataSource = self
        tableView.delegate = self
        tableView.isScrollEnabled = false
        tableView.separatorStyle = .none
        tableView.register(QDLinePathTableViewCell.self, forCellReuseIdentifier: "cell")

        contentView.addSubview(containerView)
        containerView.addSubview(tableView)
        containerView.addSubview(closeButton)
        containerView.addSubview(lineView)
        containerView.addSubview(bottomButton)
        containerView.addSubview(pricelabel)
        containerView.addSubview(changedLabel)
        containerView.addSubview(sumLabel)
        containerView.addSubview(timeLabel)
        
        closeButton.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(20)
            make.right.equalToSuperview().inset(20)
            make.width.height.equalTo(16)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().inset(20)
            make.bottom.equalToSuperview().inset(138.5 + BarDistance.TabBar.safeDistance)
            make.height.equalTo(0.5)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(20)
            make.bottom.equalTo(lineView.snp.bottom).inset(15.5)
        }
        
        bottomButton.snp.makeConstraints { (make) in
            make.right.left.equalTo(lineView)
            make.height.equalTo(44)
            make.top.equalTo(lineView.snp.bottom).offset(75.5)
        }
        
        
        pricelabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.height.equalTo(20)
            make.top.equalTo(lineView.snp.bottom).offset(15.5)
        }
        
        changedLabel.snp.makeConstraints { (make) in
            make.right.equalToSuperview().inset(20)
            make.height.top.equalTo(pricelabel)
        }
        
        sumLabel.snp.makeConstraints { (make) in
            make.left.height.equalTo(pricelabel)
            make.top.equalTo(pricelabel.snp.bottom).offset(4)
        }
        
        timeLabel.snp.makeConstraints { (make) in
            make.right.height.equalTo(changedLabel)
            make.top.equalTo(sumLabel)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    // MARK: Super
    override func showAnimated() {
        
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseIn, animations: {
            self.containerView.ritl_originY = self.ritl_height - self.containerView.ritl_height + self.containerView.layer.cornerRadius
        }, completion: nil)
    }
    
    
    override func dismissAnimated() {
        
        UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
            self.containerView.ritl_originY = self.ritl_height
        }) { (_) in
            self.removeFromSuperview()
        }
    }
    
    
    // MARK: @objc
    
    /// 关闭按钮点击
    @objc func closeButtonDidTap(){
        dismissAnimated()
    }
}


extension QDLinePathView: UITableViewDataSource,UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return linePath.stationInfos.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        if let pathCell = cell as? QDLinePathTableViewCell {//进行赋值
         
            let count = linePath.stationInfos.count
            
            //设置位置
            pathCell.isFirst = indexPath.row == 0
            pathCell.isEnd = indexPath.row == count - 1
            
            let station = linePath.stationInfos[indexPath.row]
            //设置属性
            pathCell.titleLabel.text = station.startStation
            pathCell.timeLabel.text = "(首\(station.startFirst) 末\(station.startLast))"
            pathCell.numberLabel.text = station.lineName
            pathCell.lineView.backgroundColor = station.lineId.metroSelectColor
            pathCell.circleView.backgroundColor = station.lineId.metroSelectColor
            pathCell.numberLabel.backgroundColor = station.lineId.metroSelectColor
            pathCell.countLabel.text = "\(station.stationNums)站(\(station.costTime))"
        }
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return indexPath.row == (linePath.stationInfos.count - 1) ? 28 : 60 + 28
    }
}
